/**
 * Description:录入类控件基类。主要用于抽象出录入类控件公共方法
 * Copyright: 成都和为科技有限公司 2012
 * 
 * 属性：
 *   describle  - 描述
 *   disabled - 是否可编辑 true|false
 *   default - 默认值
 *   showframe - 默认 false
 * 事件:
 *   validate - 认证
 *   onfocus - 聚焦
 *   onblur - 丢失焦点
 *   onchange - 改变值
 *   oninitdata - 在使用数据初始化调用
 *   onsavedata - 在保存数据时调用
 *   onvaluechange 值随时发生改变时调用，与onchange的区别是实时变化
 */
function Input() {}

Input.inherit(Control);

Input.prototype.init = function () {
	this._validate = true;
	this._error = "";
	Input.base.init.call(this);

    this._tiptext = "";
    var othis = this;
    $("input,textarea", this.getHTML()).bind("mouseover", function() {
        if (othis._tiptext != "") {
            WinUtil.showTip(othis.getHTML(), {title:othis._tiptext, time:90000000,
                placement:"bottom"});
        }
    });
    $("input,textarea", this.getHTML()).bind("mouseout", function() {
        if (othis._tiptext != "") {
            clearTimeout(othis._timeout);
            othis._timeout = setTimeout(function(){
                WinUtil.closeTip(othis.getHTML());
            },500);
        }
    });
}

Input.prototype.initLoad = function() {
    $(this.getHTML()).addClass("control-input");
    this._showFrame = false;
    if (this.getAttribute().showframe &&
        this.getAttribute().showframe == "true") {
        this._showFrame = true;
        this._isPos = false;
        this._frameDOM = $("<iframe></iframe>");
        $(this._frameDOM).css({
            position : "absolute",
            zIndex:1000,
            border:0,
            backgroundColor:"#fff"
        });
    }

    if (this.getAttribute()["default"]) {
    	this.setValue(this.getAttribute()["default"]);
    }
}

/**
 * 聚焦事件
 * @param {} event
 */
Input.prototype.focus = function(event) {
	var oInput = event.currentTarget;
    this.showFrame();
    this.setValidate(true);
	this.triggerAttributeEvent("onfocus");
}

/**
 * 文本内容改变事件
 * @param {} event
 * @param lengthZero
 */
Input.prototype.valuechange = function(e,lengthZero) {
    var oInput = e.srcElement||e.target;
    //去掉空格
//    oInput.value = oInput.value.replace(/^\s+|\s+$/g, "");
    if(lengthZero == "true"){//当value长度为零时是否触发onvaluechange事件
        this.triggerAttributeEvent("onvaluechange");
    }else{
        if(oInput.value.length>0){
            this.triggerAttributeEvent("onvaluechange");
        }
    }
}
/**
 * 丢失焦点事件
 * @param {} event
 */
Input.prototype.blur = function(event) {
	var oInput = event.currentTarget;
	//去掉空格
	oInput.value = oInput.value.replace(/^\s+|\s+$/g, "");
	//调用控件自带的认证方法
	var flag = this.validateControl(oInput.value);
	if (flag && this.isValidate()) {
		this.triggerAttributeEvent("validate");
		this.triggerAttributeEvent("onchange");
	}
	this.showError(false);
    this.showLength();
    this.removeFrame();
	this.triggerAttributeEvent("onblur");
    if (this._tiptext != "" && !this.getAttribute().notip) {
        WinUtil.showTip(this.getHTML(), {title:this._tiptext,
            placement:"bottom"});
    }
}

Input.prototype.validateControl = function(sValue) {
	return true;
}

Input.prototype.showLength = function() {
    if (!this.isValidate()) {
        return;
    }
    //解决控件是TextArea的BUG
    var oControl=null;
    if(this._type=="TextArea"){
        oControl=$("textarea", this.getHTML());
    }else{
        oControl=$("input", this.getHTML());
    }
    var inputWidth = oControl.width();
    if (inputWidth == 0) return;
    var value = oControl.val();
    var textWidth = value.visualLength();
    if (textWidth > inputWidth) {
        this._tiptext = value;
    } else {
        this._tiptext = "";
    }
}

/**
 * 获得错误消息
 */
Input.prototype.setValue = function() {
    this._tiptext = "";
    this.setValidate(true);
    this.showError();
}

/**
 * 获得错误消息
 */
Input.prototype.getError = function(){
	return this._error;
}

/**
 * 设置错误消息
 */
Input.prototype.setError = function(sError){
	this._error = sError;
    this._tiptext = sError;
}

/**
 * 显示错误
 */
Input.prototype.showError = function(tip) {
	if (!this.isValidate()) {
        $(this.getHTML()).addClass("has-error");
        this._tiptext = this.getError();
        if (typeof(tip)  == "undefined" || tip == true) {
//        	var scrollTop = this.getHTML().scrollTop;
        	var scrollTop = $(this.getHTML()).offset().top - 100;

    		$("body").animate({scrollTop:scrollTop}, 500);
    	
            WinUtil.showTip(this.getHTML(), {title:this._tiptext,
                placement:"bottom"});
        }
	} else {
        this._tiptext = "";
        $(this.getHTML()).removeClass("has-error");
    }
}


Input.prototype.buildResult = function(value, oData) {
    var oResult = this.buildValue(value);
    var submittag = this.getAttribute().submittag;
    if (submittag) {
        var submittag = submittag.replaceAll("'","\"");
        var submittagJson = JSON.parse(submittag);
        for (var tag in submittagJson) {
            if (this.getAttribute().check == "true") {
                for (var i = 0 ; i < oResult.length ; i++) {
                    var oRecord = oResult[i];
                    var values = oData[tag];
                    if(typeof(values)  == "undefined") {
                    	oRecord[submittagJson[tag]] = value.split(",")[i];
                    } else {
                    	oRecord[submittagJson[tag]] = values.split(",")[i];
                    }
                }
            } else {
                oResult[submittagJson[tag]] = oData[tag];
            }
        }
    }
    this.setResult(oResult);
}

Input.prototype.buildSubmit = function(oData) {
	if (typeof(oData) == "undefined") return;
    var submittag = this.getAttribute().submittag;
    if (submittag) {
        var submittag = submittag.replaceAll("'","\"");
        var submittagJson = JSON.parse(submittag);
        var oResult = this.getResult();
        if (!oResult) return;
        for (var tag in submittagJson) {
            if (this.getAttribute().check == "true") {
                var sValue = "";
                for (var j = 0 ; j < oResult.length ; j++) {
                    sValue += oResult[j][submittagJson[tag]] + ",";
                }
                if (sValue.length > 0) sValue = sValue.substring(0, sValue.length - 1);
                if(sValue) {
//                	oData[tag] = sValue;
                	this.convertValue(tag, oData, sValue);
                }
            } else {
                if (oData) {
                	this.convertValue(tag, oData, oResult[submittagJson[tag]]);
           		}
            }
    	}
    }
}

/**
 * 处理tag里面有.的情况
 * @param {} tag
 * @param {} oData 赋值数据
 * @param {} result 赋值结果
 */
Input.prototype.convertValue = function(tag, oData, result) {
	var tags = tag.split(".");
	var value = oData;
	for (var i = 0 ; i < tags.length; i++) {
		if (i == (tags.length - 1)) {
			value[tags[i]] = result;
		} else {
			if (!value[tags[i]]) {
				value[tags[i]] = new Object();
			}
			value = value[tags[i]];
		}
	}
}

Input.prototype.valueItem = function(row, tag) {
	var tags = tag.split(".");
	var value = row;
	for (var i = 0 ; i < tags.length ; i++) {
		if (value[tags[i]]) {
			value = value[tags[i]];
		} else {
			return "";
		}
	}
	return value;
}

/**
 * 设置控件可编辑
 */
Input.prototype.setEnable = function() {
	//增加描述
	if (this._attr.describle)
		$("input,textarea",this._html).attr("placeholder", this._attr.describle);
	this._disable = false;
}

/**
 * 设置不可编辑
 */
Input.prototype.setDisable = function() {
	//去掉描述
	$("input,textarea",this._html).attr("placeholder", "");
	this._disable = true;
}

/**
 * 设置不可编辑，但是可以点击
 */
Input.prototype.setReadonly = function() {
	//去掉描述
	$("input,textarea",this._html).attr("placeholder", "");
	this._readonly = true;
}

/**
 * 设置控件可编辑
 */
Input.prototype.setDisReadonly = function() {
	$("input,textarea",this._html).removeAttr("readonly");
}

Input.prototype.showFrame = function(relDom) {
    if (this._showFrame) {
        if (!this._isPos) {
            var that = this;
            setTimeout(function(){
                if (that.getType() == "DateField") {
                    var dom = $(".datetimepicker");
                } else if (that.getType() == "TimeInput") {
                    var dom = $(".clockpicker-popover");
                } else {
                    return;
                }
                $(that._frameDOM).css({
                    top:dom.offset().top - 10,
                    left:dom.offset().left - 10,
                    width:dom.width() + 30,
                    height:dom.height() + 20
                });
                that._isPos = true;
            }, 500);
        }
        $("body").append(this._frameDOM);
    }
}

Input.prototype.removeFrame = function() {
    if (this._showFrame) {
        $(this._frameDOM).remove();
    }
}
/*
 * 按回车键跳到下一个文本框
 */
$(document).ready(function () {
	$('input:text:first').focus();
    var $inp = $('input:text');
    $inp.bind('keydown', function (e) {
        var key = e.which;
        if (key == 13) {
            e.preventDefault();
            var nxtIdx = $inp.index(this) + 1;
            $(":input:text:eq(" + nxtIdx + ")").focus();
        }
    });
});
